package mongodao

import (
	mongomodel "mygame/app/model/mongoModel"
	mongopkg "mygame/pkg/mongoPkg"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
)

type User struct{}

func (u User) db() *mongo.Collection {
	return mongopkg.DB.Collection(mongomodel.User{}.TableName())
}

func (u User) AddUser(user mongomodel.User) (*mongomodel.User, error) {
	uid, _ := Counter{}.GetNextID("userId")
	user.Uid = uid
	user.CreatedAt = time.Now()
	res, err := u.db().InsertOne(mongopkg.Ctx, user)
	if err != nil {
		return nil, err
	}
	user.Id = res.InsertedID.(primitive.ObjectID).Hex()
	return &user, nil
}

func (u User) GetUserByUsername(username string) (mongomodel.User, error) {
	user := mongomodel.User{}

	// a := bson.M{"username": username}
	// b := bson.D{
	// 	{Key: "username", Value: "test"},
	// 	{Key: "abc", Value: "123"},
	// }

	err := u.db().FindOne(mongopkg.Ctx, bson.M{"username": username}).Decode(&user)
	return user, err
}

func (u User) GetUserByOpenid(openid string) (*mongomodel.User, error) {
	var user mongomodel.User
	err := u.db().FindOne(mongopkg.Ctx, bson.M{"openid": openid}).Decode(&user)
	if err != nil {
		user.Openid = openid
		res, err := u.AddUser(user)
		if err != nil {
			return nil, err
		}
		return res, nil
	}
	return &user, nil
}

func (u User) GetUserByUid(uid int64) (mongomodel.User, error) {
	user := mongomodel.User{}
	err := u.db().FindOne(mongopkg.Ctx, bson.M{"uid": uid}).Decode(&user)
	return user, err
}

func (u User) GetUserById(id string) (mongomodel.User, error) {
	user := mongomodel.User{}
	objectId, _ := primitive.ObjectIDFromHex(id)
	err := u.db().FindOne(mongopkg.Ctx, bson.M{"_id": objectId}).Decode(&user)
	return user, err
}
